# -*- coding:utf-8 -*-
# --author： jingfeng 
# time: 2018/11/16
import re

from bs4 import BeautifulSoup
import requests
from fake_useragent import UserAgent

ua = UserAgent()
headers = {'User-Agent': ua.random}


def get_id_name():
    download_url = 'http://music.163.com/song/media/outer/url?id={}.mp3'
    url = 'https://music.163.com/discover/toplist'
    response = requests.get(url=url, headers=headers)
    html = response.text
    soup = BeautifulSoup(html, 'lxml')
    # print(soup.prettify())

    toplist = soup.find_all(id="song-list-pre-cache")[0]

    for a in toplist.select('a'):
        # print(a['href'])
        id =re.findall(r'id=(\d+)',a['href'])[0]
        download_url = download_url.format(id)
        response = requests.get(download_url,headers=headers)
        name = a.string
        content = response.content
        print(content)
        try:
            with open('music/'+name +'.mp3','wb')as f:
                f.write(content)
            print(name + '下载完成')
        except:
            pass


get_id_name()


